﻿using System;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ChatAJAX.Models;
using System.Web.Security;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Net.Http.Formatting;
using System.IO;
using System.Net;

namespace ChatAJAX.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/
        public static HttpClient client;
        public ActionResult Index()
        {
            if (null == client)
            {
                client = new HttpClient();
                client.BaseAddress = new Uri("http://localhost:49509/");
                client.DefaultRequestHeaders.Accept.Add(
                  new MediaTypeWithQualityHeaderValue("application/json"));
            }
            return View();
        }

        public ActionResult Register()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                // Attempt to register the user
                MembershipCreateStatus createStatus;
                CreateUser(model, out createStatus);
                if (createStatus == MembershipCreateStatus.Success)
                {
                    HttpPostedFileBase file = Request.Files[0] as HttpPostedFileBase;
                    if (file.ContentLength > 0)
                    {
                        RequestImage(file, model.UserName);
                    }
                    Session["login"] = "true";
                    Session["username"] = model.UserName;
                    Session["Mode"] = "0";
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError("", ErrorCodeToString(createStatus));
                }
            }
            // If we got this far, something failed, redisplay form
            return View(model);
        }

        public ActionResult Logon(String id, String Mode)
        {
            Session["login"] = "true";
            Session["username"] = id;
            Session["Mode"] = Mode;
            return RedirectToAction("Index", "Home");
        }

        public ActionResult GetAccessToken(String oauth_token, String oauth_verifier, String UserName)
        {
            //Get requesttoken
            String URL = "http://localhost:49509/api/yahoo/GetAccessToken";
            String urlrequest = String.Format("{0}?OauthToken={1}&OauthVerify={2}&UserName={3}",
                URL, oauth_token, oauth_verifier, UserName);
            HttpWebRequest Request = HttpWebRequest.Create(urlrequest.Trim()) as HttpWebRequest;
            Request.Accept = "text/plain";
            using (HttpWebResponse response = Request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    // Create Stream Reader                   
                    StreamReader reader = new StreamReader(response.GetResponseStream());
                    // Return                  
                    String resp = reader.ReadToEnd().Replace("\"", "");
                    if (resp == "Success")
                    {
                        Session["login"] = "true";
                        Session["username"] = UserName;
                        Session["Mode"] = "1";
                    }
                    else Session["Error"] = "Account invalid";
                }
            }
            return RedirectToAction("Index", "Home");
        }

        [HttpGet]
        public ActionResult Logout(string act, string con)
        {
            Session.Clear();
            //clear cookie
            if (this.ControllerContext.HttpContext.Request.Cookies.AllKeys.Contains("Cookie"))
            {
                HttpCookie cookie = this.ControllerContext.HttpContext.Request.Cookies["Cookie"];
                cookie.Expires = DateTime.Now.AddDays(-1);
                this.ControllerContext.HttpContext.Response.Cookies.Add(cookie);
            }
            Session["Mode"] = "0";
            return RedirectToAction("Index", "Home");
        }

        private void CreateUser(RegisterModel model, out MembershipCreateStatus createStatus)
        {
            // Create the JSON formatter.
            MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();

            Account acc = new Account();
            acc.Email = model.Email;
            acc.PassWord = model.Password;
            acc.UserName = model.UserName;
            // Use the JSON formatter to create the content of the request body.
            HttpContent content = new ObjectContent<Account>(acc, jsonFormatter);

            // Send the request.
            var resp = client.PostAsync("api/Account", content).Result;
            if (resp.IsSuccessStatusCode)
            {
                String error = resp.Content.ReadAsAsync<String>().Result;
                if (error == "SC") //Duplicated username
                {
                    createStatus = MembershipCreateStatus.Success;
                    return;
                }
                if (error == "DU") //Duplicated username
                {
                    createStatus = MembershipCreateStatus.DuplicateUserName;
                    return;
                }
                if (error == "DE") //Duplicated Email
                {
                    createStatus = MembershipCreateStatus.DuplicateEmail;
                    return;
                }
            }
            createStatus = MembershipCreateStatus.UserRejected;
        }

        private bool RequestImage(HttpPostedFileBase file, String username)
        {
            // Create the JSON formatter.
            MediaTypeFormatter jsonFormatter = new JsonMediaTypeFormatter();
            // Use the JSON formatter to create the content of the request body.
            byte[] buf;  // byte array
            Stream stream = file.InputStream;  //initialise new stream
            buf = new byte[stream.Length];  //declare arraysize
            stream.Read(buf, 0, buf.Length); // read from stream to byte array
            HttpContent content = new ObjectContent<byte[]>(buf, jsonFormatter);

            // Send the request.
            var resp = client.PostAsync("api/Picture/" + username, content).Result;
            if (resp.IsSuccessStatusCode)
            {
                return true;
            }
            return false;
        }

        #region Status Codes
        private static string ErrorCodeToString(MembershipCreateStatus createStatus)
        {
            // See http://go.microsoft.com/fwlink/?LinkID=177550 for
            // a full list of status codes.
            switch (createStatus)
            {
                case MembershipCreateStatus.DuplicateUserName:
                    return "User name already exists. Please enter a different user name.";

                case MembershipCreateStatus.DuplicateEmail:
                    return "A user name for that e-mail address already exists. Please enter a different e-mail address.";
                default:
                    return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator.";
            }
        }
        #endregion
    }
}
